import {
	userApi
} from '../ajax/api.js'
export default {
	login(invite_code = '') {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				console.log(loginRes)
				let code = loginRes.code;
				// if (!_this.isCanUse) {
				if (!uni.getStorageSync('isCanUse')) {
					//非第一次授权获取用户信息
					uni.getUserInfo({
						provider: 'weixin',
						success: function(infoRes) {
							//获取用户信息后向调用信息更新方法
							let nickName = infoRes.userInfo.nickName; //昵称
							let avatarUrl = infoRes.userInfo.avatarUrl; //头像
						}
					});
				}
				//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
				if (uni.getStorageSync('userinfo')) { // 如果本地获取过权限
					uni.request({
						url: userApi.userLogun,
						data: {
							// app_id: 'wx092fc30ac707fa52',
							iv: uni.getStorageSync('iv'),
							encrypted_data: uni.getStorageSync('encrypted_data'),
							app_id: '1',
							code: code,
							referee_id: '', // id 来源
							unionid: '',
							user_info: uni.getStorageSync('userinfo'),
							invite_code: invite_code
						},
						method: 'GET',
						header: {
							'content-type': 'application/json'
						},
						success: (res) => {
							if (res.data.code === -1) { // 如果还没有通过邀请码验证
								return uni.showToast({
									icon: 'none',
									title: res.data.msg
								})
							}
							if (res.data.code === '1' && res.data.data) {
								uni.setStorageSync('token', res.data.data.token)
								uni.setStorageSync('user_id', res.data.data.user_id)
								getApp().globalData.user_id = res.data.data.user_id
								uni.switchTab({
									url: '../index/index'
								})
							}
						}
					});
				}
			},
		});
	},
	wxGetUserInfo(invite_code) {
		let _this = this;
		uni.getUserInfo({
			provider: 'weixin',
			success: function(infoRes) {
				console.log(infoRes)
				let wxUserInfo = JSON.parse(infoRes.rawData)
				// nick_name avatar_url  gender phone country province city  district
				let userinfo = {
					nick_name: wxUserInfo.nickName,
					avatar_url: wxUserInfo.avatarUrl,
					gender: wxUserInfo.gender,
					phone: '',
					country: wxUserInfo.country,
					province: wxUserInfo.province,
					city: wxUserInfo.city,
					district: wxUserInfo.district // 地区
				}
				uni.setStorageSync('userinfo', JSON.stringify(userinfo));
				uni.setStorageSync('encrypted_data', infoRes.encryptedData)
				uni.setStorageSync('iv', infoRes.iv)
				// let nickName = infoRes.userInfo.nickName; //昵称
				// let avatarUrl = infoRes.userInfo.avatarUrl; //头像
				try {
					uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
					_this.login(invite_code?invite_code:null);
				} catch (e) {}
			},
			fail(res) {}
		});
	}
}
